import axios from 'axios'
import router from '../router'
import store from '../store/index'
import ApiResult from '../class/ApiResult'
import { ElMessage } from 'element-plus'
import { FormatToken } from '../tools'
import Calendar from '../class/Cale'
const instance = axios.create({
    timeout: 3000,
    headers: {
        "Content-Type": "application/json",
        // "Authorization":"Bearer "+ token()
    }
})

//拦截请求
instance.interceptors.request.use(
    req => {
        //写自己的逻辑，全局状态管理需要在这里获取，否则会提示没有初始化应用
        req.headers.Authorization = "Bearer " + store().token
        return req
    }
)

//拦截响应
instance.interceptors.response.use(
    response => {
        // 拿到请求结果统一返回，并设置返回结果
        const res: ApiResult = response.data
        if (!res.IsSuccess) {
            ElMessage.error(res.Message);
        }
        //对于业务模块只需要结果，无需做验证提示
        return res.Result
    },
    //请求异常走这里
    async error => {
        const originalRequest = error.config
        if (!originalRequest) return Promise.reject(error)

        //根据不同状态码做出不同的响应
        //1：401表示没权限直接跳转到登录 
        //2：_retry表示是否应该重试
        //3：RefreshTokenNum 表示重试次数
        //4：如果Pinia里面的全局状态等于空，则说明未登录不进行刷新逻辑
        if (error.response.status == 401 && !originalRequest._retry && store().RefreshTokenNum < 2 && store().token != "") {
            console.log("进入刷新机制")
            originalRequest._retry = true
            const newToken = (await getNewToken(FormatToken(store().token)?.Id!)).data.Result as string
            if (newToken) {
                let num = store().RefreshTokenNum + 1
                store().$patch({ token: newToken, RefreshTokenNum: num })
                instance.defaults.headers.common['Authorization'] = `Bearer ${newToken}`
                return instance(originalRequest)
            }
        } else if (error.response.status == 401) {
            router.push({ path: "/login" })
        } else if (error.response.status == 404) {
            router.push({ path: "/abc123" })
        } else if (error.response.status == 500) {
            ElMessage.error("内部服务器错误!")
        } else if (error.response.status > 500) {
            ElMessage.error("服务器错误请联系后端人员!")
        } else if (error.indexOf("time out") > 1) {
            ElMessage.error("接口超时")
        }


        //请求失败返回错误信息
        return Promise.reject(error)
    }
)

export const getToken = (obj: {}) => {
    const token = instance.post(`/api/Login/GetToken`, obj)
    return token;
}

export const getNewToken = (userId: string) => {
    return axios.get(`/api/Login/RefreshToken?userId=${userId}`)
}

//=========菜单接口相关==========
export const getTreeMenu = (obj: {}) => {
    return instance.post(`/api/Menu/GetMenus`, obj)
}
export const addMenu = (obj: {}) => {
    return instance.post(`api/Menu/AddMenu`, obj)
}
export const editMenu = (obj: {}) => {
    return instance.post(`/api/Menu/EditMenu`, obj)
}
export const delMenu = (index: number) => {
    return instance.get(`/api/Menu/DelMenu?id=${index}`)
}
export const getMenuRoleRelations = (rid: string) => {
    return instance.get(`/api/Menu/GetMenuRoleRelations?roleId=${rid}`)
}
export const settingMenu = (rid?: string, mid?: string) => {
    return instance.get(`/api/Menu/SettingMenu?roleId=${rid}&menuId=${mid}`)
}
//=============用户接口相关==============
export const getUsers = async (obj: {}) => {
    return await instance.post("/api/User/GetUsers", obj)
}
export const addUser = (obj: {}) => {
    return instance.post("/api/User/AddUser", obj)
}
export const editUser = (obj: {}) => {
    return instance.post("/api/User/EditUser", obj)
}
export const delUser = (uid: string) => {
    return instance.get(`/api/User/DelUser?id=${uid}`)
}
export const editPerson = (obj: {}) => {
    return instance.post("/api/User/EditUser", obj)
}
export const editUserFile = async (obj: {}) => {
    return await instance.post("/api/User/EditUserFile", obj)
}
export const uploadFile = (mode: string) => {
    return instance.post(`/api/File/UploadFile?model=${mode}`)
}
export const getCales = (day: string): Array<Calendar> => {
    return instance.get(`/api/User/GetCales?day=${day}`) as any
}
export const addCale = (obj: {}) => {
    return instance.post("/api/User/CaleAdd", obj)
}
export const editCale = (obj: {}) => {
    return instance.post("/api/User/CaleEdit", obj)
}

//================角色相关=================
export const getRoles = (obj: {}) => {
    return instance.post(`/api/Role/GetRoles`, obj)
}
export const addRole = (obj: {}) => {
    return instance.post(`/api/Role/AddRole`, obj)
}
export const delRole = (id: string) => {
    return instance.get(`/api/Role/DelRole?id=${id}`)
}
export const editRole = (obj: {}) => {
    return instance.post(`/api/Role/EditRole`, obj)
}
export const getUserRoleRelations = (uid: string | undefined) => {
    return instance.get(`/api/Role/GetUserRoleRelations?userId=${uid}`)
}
export const settingUserRole = (uid: string | undefined, roleIds: string | undefined) => {
    return instance.get(`/api/Role/SettingUserRole?userId=${uid}&roleIds=${roleIds}`)
}